/**
 * @author hdeom
 * @date 2014. 1. 17.
 *
*/

package h.d.bluetooth.visitor;

import h.d.bluetooth.visitor.common.BluetoothHandler;
import h.d.bluetooth.visitor.common.VaE;

import java.util.Calendar;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author hdeom
 * @date 2014. 1. 17.
 *
 */
public class BluetoothService extends Service{
	public static final String TAG = "BluetoothService";

	public int mScanCycle;
	public String mScanTime;

	private BroadcastReceiver time_receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Message msg = Message.obtain();

			if(TextUtils.equals(action, Intent.ACTION_TIME_TICK)){

				if(VaE.HD) Log.d(TAG, "time_tick onReceive ");

				Calendar Clock = Calendar.getInstance();
				String date = VaE.mm.format(Clock.getTime());

				msg.what = VaE.BLUETOOTH_SCAN;

				if(TextUtils.isEmpty(mScanTime)){
					mScanTime = date;
					BluetoothHandler.sendMessage(msg);
					return;
				}

				if(Integer.parseInt(mScanTime)+mScanCycle <= Integer.parseInt(date)){
					mScanTime = date;
					BluetoothHandler.sendMessage(msg);
				}
			}


		}
	};

	@Override
	public void onCreate() {
		super.onCreate();
		if(VaE.HD) Log.d(TAG, " onCreate ");
		IntentFilter intentfilter = new IntentFilter();

		intentfilter.addAction(Intent.ACTION_TIME_TICK);
		registerReceiver(time_receiver , intentfilter);

		mScanCycle = Integer.parseInt(App.getPreferenceValue(App.SCAN_CYCLE, "5"));


	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(VaE.HD) Log.d(TAG, " onStartCommand ");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if(VaE.HD) Log.d(TAG, " onDestroy ");
		unregisterReceiver(time_receiver);

	}


}
